package com.gujiangbo.es;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gujiangbo.es.entity.School;
import com.sun.istack.internal.NotNull;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;
import java.util.List;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2022/4/28 19:47
 * @Version: 1.0
 * @Description:
 */
public class ElasticsearchUtils {
    private static RestHighLevelClient client = ElasticSearchClient.getInstance();

    /**
     * 创建索引--创建数据库
     *
     * @param indices 索引参数
     * @return
     * @throws Exception
     */
    public static CreateIndexResponse createIndices(@NotNull String indices) {
        CreateIndexResponse response = new CreateIndexResponse(false, false, "000000000000");
        try {
            if (!existsIndices(indices)) {
                response = client.indices().create(new CreateIndexRequest(indices), RequestOptions.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // ElasticSearchClient.close();
        }
        return response;
    }

    /**
     * 查询索引是否存在
     *
     * @param indices
     * @return
     * @throws IOException
     */
    public static boolean existsIndices(@NotNull String indices) throws IOException {
        return client.indices().exists(new GetIndexRequest(indices), RequestOptions.DEFAULT);
    }

    /**
     * 获取索引对象信息
     *
     * @param indices
     * @return
     */
    public static GetIndexResponse getIndicesObj(@NotNull String indices) {
        GetIndexResponse indexResponse = null;
        try {
            indexResponse = client.indices().get(new GetIndexRequest(indices), RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //  ElasticSearchClient.close();
        }
        return indexResponse;
    }

    /**
     * 删除索引
     *
     * @param indices
     * @return
     */
    public static AcknowledgedResponse deleteIndices(@NotNull String indices) {
        AcknowledgedResponse response = null;
        try {
            response = client.indices().delete(new DeleteIndexRequest(indices), RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ElasticSearchClient.close();
        }
        return response;
    }

    /**
     * 添加数据
     *
     * @param object
     * @return
     */
    public static IndexResponse addData(@NotNull School object) {
        IndexResponse result = null;
        try {
            IndexRequest request = new IndexRequest();
            request.index(object.index).id(object.getsId());
            // 将对象转换为json
            ObjectMapper mapper = new ObjectMapper();
            String schoolJson = mapper.writeValueAsString(object);
            request.source(schoolJson, XContentType.JSON);
            result = client.index(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // ElasticSearchClient.close();
        }
        return result;
    }

    /**
     * 更新数据
     *
     * @param object
     * @return
     */
    public static UpdateResponse updateData(@NotNull School object) {
        UpdateResponse response = null;
        try {
            UpdateRequest request = new UpdateRequest();
            request.index(object.index).id(object.getsId());
            // 将对象转换为json
            ObjectMapper mapper = new ObjectMapper();
            String schoolJson = mapper.writeValueAsString(object);
            request.doc(schoolJson, XContentType.JSON);
            response = client.update(request, RequestOptions.DEFAULT);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ElasticSearchClient.close();
        }
        return response;

    }

    /**
     * 根据ID查询数据
     *
     * @param index
     * @param id
     * @return
     */
    public static GetResponse getObjectByID(@NotNull String index, @NotNull String id) {
        GetResponse response = null;
        try {
            GetRequest request = new GetRequest();
            request.index(index).id(id);
            response = client.get(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ElasticSearchClient.close();
        }
        return response;
    }

    /**
     * 删除文档数据
     *
     * @param index
     * @param id
     * @return
     */
    public static DeleteResponse deleteObject(@NotNull String index, @NotNull String id) {
        DeleteResponse delete = null;
        try {
            DeleteRequest request = new DeleteRequest();
            request.index(index).id(id);
            delete = client.delete(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ElasticSearchClient.close();
        }
        return delete;
    }

    /**
     * 批量增加文档数据
     *
     * @param list ''
     */
    public static BulkResponse batchInsertData(@NotNull List<School> list) {
        BulkResponse response = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            BulkRequest bulkRequest = new BulkRequest();
            list.forEach(elem -> {
                IndexRequest indexRequest = new IndexRequest();
                indexRequest.index(elem.index).id(elem.getsId()).source(XContentType.JSON,
                        "sId", elem.getsId(), "name", elem.getName(),
                        "address", elem.getAddress(), "anniversary", elem.getAnniversary(), "schoolmaster", elem.getSchoolmaster());
                bulkRequest.add(indexRequest);
            });


            response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ElasticSearchClient.close();
        }
        return response;
    }

    /**
     * 批量删除文档数据
     */
    public static BulkResponse batchDelData(@NotNull String index, List<String> ids) {
        BulkResponse response = null;
        try {
            BulkRequest request = new BulkRequest();
            ids.forEach(elem -> request.add(new DeleteRequest().index(index).id(elem)));
            response = client.bulk(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ElasticSearchClient.close();
        }
        return response;
    }


    /**
     * 查询全部
     *
     * @param index 索引库
     * @return SearchResponse
     */
    public static SearchResponse searchDataByMatch(String index) {
        SearchResponse response = null;
        try {
            SearchRequest request = new SearchRequest();
            request.indices(index);
            request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ElasticSearchClient.close();
        }
        return response;

    }

}
